import {Tab} from "@/lib/types";

/**
 * 框架标签页状态管理机
 */
export default {
    tabActive: "",
    tabOpened: [] as Array<Tab>,

    /**
     * 增加一个tab页
     * @param name 页面名称(英文代码)
     * @param title 标题
     * @param component 组件
     * @param closable 是否可以关闭
     */
    addTab(name: string, title: string, component: string, closable: boolean = true) {
        this.tabOpened.push({
            name,
            title,
            closable
        });
    },
    /**
     * 设置系统首页
     * @param name 首页名称(英文代码)
     * @param title 页面标题
     */
    homepage(name: string, title: string) {
        this.tabOpened.push({
            name,
            title,
            closable:false,
        });
        this.tabActive=name;
    },
    /**
     * 激活当前页
     * @param name 页名
     */
    active(name: string) {
        this.tabActive = name;
    },

    /**
     * 关闭 tab 页面
     * @param tabName tab 名称
     */
    close(tabName: string) {
        const index = this.tabOpened.findIndex(tab => tab.name === tabName);
        const removed = this.tabOpened[index];
        this.tabOpened.splice(index, 1);
        // 移除的是当前 tab
        if (removed.name === this.tabActive && this.tabOpened.length > 0) {
            let activeIndex = index - 1;
            if (activeIndex < 0) {
                activeIndex = 0;
            }
            this.active(this.tabOpened[activeIndex].name)
        }
    }
}